package sky.cin.framework.nio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public class NioUtils<T> {

    public static void write(SocketChannel client, String msg) throws IOException {
        client.write(ByteBuffer.wrap(msg.getBytes(StandardCharsets.UTF_8)));
    }

    public static String read(SocketChannel client) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        int len;
        StringBuilder result = new StringBuilder();
        while ((len = client.read(buffer)) > 0) {
            buffer.flip();
            result.append(new String(buffer.array(), 0, len));
        }
        return result.toString().trim();
    }

    public static String doInvoke(SocketChannel client, String request, Selector selector) {
        try {
            write(client, request);
            selector.select();
            return read(client);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
